package domotica.gui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreeSelectionModel;

import domotica.houseowner.HouseOwner;

@SuppressWarnings("serial")
public class DomoticaGUI extends JFrame implements TreeSelectionListener{
	
	private Map<String, SlidersJPanel> jPanelCache;
	private HouseOwner houseOwner;
	
	private JPanel mainPanel;
	private JTree actuatorSensorNamesTree;
	private ActuatorSensorGUI actuatorSensorPanel;
	private JSplitPane splitPane;	

	public DomoticaGUI(HouseOwner houseOwner, int width, int height) {
		
		this.houseOwner = houseOwner;
		this.jPanelCache = new HashMap<String, SlidersJPanel>();
		
		this.setIconImage(DomoticaGUI.createImage("images/logoframe1.gif"));
		this.setSize(width, height);		
		this.setLocationByPlatform(true);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setTitle("Domotica");
		
        mainPanel = new JPanel(new GridLayout(1,0));    
        mainPanel.setOpaque(true);
        
        // Creazione radice dell'albero
        DefaultMutableTreeNode top =
            new DefaultMutableTreeNode("ActuatorsSensors");
        
        createNodes(top);

        // Crea un albero che permette di selezionare un elemento alla volta
        actuatorSensorNamesTree = new JTree(top);
        actuatorSensorNamesTree.getSelectionModel().setSelectionMode
                (TreeSelectionModel.SINGLE_TREE_SELECTION);
        
        ImageIcon leafIcon = createImageIcon("images/gears.gif");
        if (leafIcon != null) {
            DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
            renderer.setLeafIcon(leafIcon);
            actuatorSensorNamesTree.setCellRenderer(renderer);
        } else {
            System.err.println("Leaf icon missing; using default.");
        }
        
        actuatorSensorNamesTree.addTreeSelectionListener(this);
        
        JScrollPane treeView = new JScrollPane(actuatorSensorNamesTree);
               
        actuatorSensorPanel = new ActuatorSensorGUI(this, houseOwner);
        
        splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
        splitPane.setTopComponent(treeView);
        splitPane.setBottomComponent(actuatorSensorPanel);
        
        Dimension minimumSize = new Dimension(100, 200);
        actuatorSensorPanel.setMinimumSize(minimumSize);
        treeView.setMinimumSize(minimumSize);
        splitPane.setDividerLocation(175); 
    
        mainPanel.add(splitPane);
        
		this.add(mainPanel,BorderLayout.CENTER);
        
	}

	/**
	 * Popola l'albero con i nomi dei componenti connessi sul server
	 */
	private void createNodes(DefaultMutableTreeNode top) {
	
		for(String name: this.houseOwner.getActuatorsSensorsNameList()){
			top.add(new DefaultMutableTreeNode(name));
		}
		
	}

	public void valueChanged(TreeSelectionEvent e) {
		
		DefaultMutableTreeNode node = (DefaultMutableTreeNode)
        actuatorSensorNamesTree.getLastSelectedPathComponent();

		if (node == null) 
			return;
		
		String componentName = (String) node.getUserObject();
		
		if (node.isLeaf()){
			if(this.jPanelCache.containsKey(componentName)){ 
				actuatorSensorPanel.setActuatorSensorParametersSliders(this.jPanelCache.get(componentName), componentName);
			}else{
				actuatorSensorPanel.setActuatorSensorParametersSliders(componentName);
			}
		}
	}
	
	protected static ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = DomoticaGUI.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn't find file: " + path);
            return null;
        }
    }
	
	protected static Image createImage(String path){
		
		BufferedImage image = null;
        try {
            image = ImageIO.read(DomoticaGUI.class.getResource(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
		return image;

	}
	
	/**
	 * Aggiunge un oggetto grafico associato ad un ActuatorSensor alla
	 * cache dell'interfaccia grafica per evitare di doverlo ricostruire
	 * piu' volte
	 */
	public void addActuatorSensorCacheElement(String actuatorSensorName,
			SlidersJPanel sliderJPanel) {
		this.jPanelCache.put(actuatorSensorName, sliderJPanel);
		
	}
	
}